package com.efounder.chat.db;

import android.content.Context;

import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.model.ApplyGroupNotice;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.Group;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.model.UserEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.db.MessageDBManager;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * IM数据库操作
 *
 * @author YQS
 */
public class WeChatDBManager {
    private UserDBManager userDBManager;//用户数据库管理类
    private GroupDBManager groupDBManager;//群组数据库管理类
    private NewFriendsDBManager newFriendsDBManager;//新的好友数据库管理类
    private FriendsDBManager friendsDBManager;//好友管理
    private ChatListDBManager chatListDBManager;//聊天列表管理
    private MessageDBManager messageDBManager;//消息管理
    private GroupNoticeDBManager groupNoticeDBManager;//群通知管理

    private Context mContext;
    private int loginUserId;//登录的用户id

    private volatile static WeChatDBManager weChatDBManager;


    public static WeChatDBManager getInstance() {
        if (weChatDBManager == null) {
            synchronized (WeChatDBManager.class) {
                if (weChatDBManager == null) {
                    weChatDBManager = new WeChatDBManager(AppContext.getInstance());
                }
            }
        }
        return weChatDBManager;
    }

    public static void realese() {
        weChatDBManager = null;
    }

    /**
     * @see WeChatDBManager#getInstance()
     * 为避免以前代码报错这里暂时使用public，新写代码请使用单例
     */
    @Deprecated
    public WeChatDBManager(Context context) {
        mContext = context.getApplicationContext();
        String imUserId = EnvironmentVariable.getProperty(CHAT_USER_ID, "0");
        if (imUserId.equals("")) {
            imUserId = "0";
        }
        loginUserId = Integer.valueOf(imUserId);
    }


    /**
     * 新增或者保存好友
     *
     * @param user
     */
    public void insertOrUpdateUser(User user) {
        userDBManager = getUserDBManager();
        friendsDBManager = getFriendsDBManager();

        try {
            userDBManager.insertOrReplace(user);
            //friendsDBManager.insertOrReplce(user);
            //  User isExistsUser = friendsDBManager.queryById(user.getId(), loginUserId);
            friendsDBManager.insertOrReplce(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // }

    }

    /**
     * 新增或者保存好友
     *
     * @param users
     */
    public void insertOrUpdateUser(List<User> users) {
        userDBManager = getUserDBManager();
        friendsDBManager = getFriendsDBManager();
        if (users != null) {
            //插入用户表中
            userDBManager.insertOrReplace(users);

            for (User user : users) {
                try {
                    insertOrUpdateFriendUser(user);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    /**
     * 这个方法当从服务器请求好友的时候调用，本地有此好友，就不向friend表中插入
     * 插入或者更新好友表
     *
     * @param user
     */
    public void insertOrUpdateFriendUser(User user) {
        friendsDBManager = getFriendsDBManager();

        try {
//            User isExistsUser = friendsDBManager.queryById(user.getId());
//            if (isExistsUser != null) {
//                isExistsUser.setNickName(user.getNickName());
//                isExistsUser.setAvatar(user.getAvatar());
//                isExistsUser.setReMark(user.getReMark());
//                isExistsUser.setSigNature(user.getSigNature());
//                isExistsUser.setName(user.getName());
//                friendsDBManager.insertOrReplce(isExistsUser);
//            } else {
//                friendsDBManager.insertOrReplce(user);
//            }

            friendsDBManager.insertOrReplce(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 新增或者保存公众号
     *
     * @param user
     */
    public void insertOfficialNumber(User user) {
        userDBManager = getUserDBManager();
        friendsDBManager = getFriendsDBManager();
        try {
            userDBManager.insertOrReplace(user);
            User tempUser = getOneOfficialNumber(user.getId());
            if (tempUser != null) {
                user.setIsBother(tempUser.getIsBother());
                user.setIsTop(tempUser.getIsTop());
            }
            friendsDBManager.insertOrReplce(user);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 新增或者保存公众号
     *
     * @param users
     */
    public void insertOfficialNumber(List<User> users) {
        userDBManager = getUserDBManager();
        friendsDBManager = getFriendsDBManager();
        try {
            if (users != null) {
                for (User user : users) {
                    insertOfficialNumber(user);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 取消关注公众号
     */
    public void cannalFocusOfficialNumber(int userId) {
        userDBManager = getUserDBManager();
        friendsDBManager = getFriendsDBManager();
        try {
            userDBManager.delete(userId);
            friendsDBManager.delete(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 设置好友置顶或免打扰
     *
     * @param user
     */
    public void setFriendIsTopOrBother(User user) {
        friendsDBManager = getFriendsDBManager();
        try {
            friendsDBManager.updateIsTopOrBother(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置群组置顶或免打扰
     *
     * @param group
     */
    public void setGroupIsTopOrBother(Group group) {
        groupDBManager = getGroupDBManager();
        try {
            groupDBManager.updateIsTopOrBother(group);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向user表中插入信息
     *
     * @param user
     */
    public void insertUserTable(User user) {
        userDBManager = getUserDBManager();
        try {
            userDBManager.insertOrReplace(user);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 新增或者更新好友申请
     *
     * @param user
     */
    public void insertSendNewFriendApply(User user) {

        newFriendsDBManager = getNewFriendsDBManager();
        userDBManager = getUserDBManager();
        try {
            userDBManager.insertOrReplace(user);
            newFriendsDBManager.insertOrUpdate(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 对方拒绝你的好友申请
     *
     * @param user
     */
    public void refuseApplyFriend(User user) {
        newFriendsDBManager = getNewFriendsDBManager();
        try {
            newFriendsDBManager.insertOrUpdate(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 删除好友请求
     *
     * @param userId
     */
    public void deleteApplyFriend(int userId) {
        newFriendsDBManager = getNewFriendsDBManager();
        try {
            newFriendsDBManager.delete(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增或更新群通知
     *
     * @param notice
     */
    public void insertOrUpdateGroupNotice(ApplyGroupNotice notice) {

        groupNoticeDBManager = getGroupNoticeDBManager();
        try {
            groupNoticeDBManager.insertOrUpdate(notice);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 新增或更新群通知
     *
     * @param list
     */
    public void insertOrUpdateGroupNotice(List<ApplyGroupNotice> list) {

        groupNoticeDBManager = getGroupNoticeDBManager();
        // userDBManager = getUserDBManager();
        try {
            // userDBManager.insertOrReplace(notice);
            groupNoticeDBManager.insertOrUpdate(list);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 更新群通知（只是更新）
     *
     * @param
     */
    public void updateGroupNotice(ApplyGroupNotice notice) {

        groupNoticeDBManager = getGroupNoticeDBManager();

        try {
            groupNoticeDBManager.update(notice);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置所有的群通知未读为已读
     */
    public void setAllGroupNoticeIsRead() {
        groupNoticeDBManager = getGroupNoticeDBManager();
        try {
            groupNoticeDBManager.setAllIsRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除群通知
     *
     * @param groupId
     * @param userId
     */
    public void deleteGroupNotice(int groupId, int userId) {
        groupNoticeDBManager = getGroupNoticeDBManager();
        try {
            groupNoticeDBManager.delete(userId, groupId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接受好友申请
     *
     * @param user
     */
    public void agreeNewFriendApply(User user) {
        newFriendsDBManager = getNewFriendsDBManager();
        friendsDBManager = getFriendsDBManager();
        userDBManager = getUserDBManager();

        try {
            newFriendsDBManager.insertOrUpdate(user);
//            newFriendsDBManager.delete(user);
            friendsDBManager.insertOrReplce(user);
            userDBManager.insertOrReplace(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接受加群申请
     *
     * @param applyGroupNotice
     */
    public void agreeApplyGroup(ApplyGroupNotice applyGroupNotice) {
        groupNoticeDBManager = getGroupNoticeDBManager();
        groupDBManager = getGroupDBManager();
        userDBManager = getUserDBManager();
        try {
            groupNoticeDBManager.insertOrUpdate(applyGroupNotice);
            groupDBManager.insertOrUpdateUser(applyGroupNotice.getUserId(), applyGroupNotice.getGroupId());
            if (applyGroupNotice.getUser() != null) {
                userDBManager.insertOrReplace(applyGroupNotice.getUser());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 更新新的好友
     *
     * @param user
     */
    public void updateNewFriend(User user) {

        newFriendsDBManager = getNewFriendsDBManager();

        try {
            //标记setidread 为true
            newFriendsDBManager.insertOrUpdate(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 所有好友请求未读变为已读
     *
     * @return
     */
    public void updateAllNewFriendsSetIsRead() {
        newFriendsDBManager = getNewFriendsDBManager();
        try {
            //标记setidread 为true
            newFriendsDBManager.updateAllNewFriendsSetIsRead();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 得到新的好友未读的数量
     *
     * @param
     */
    public int getNewFriendUnread() {

        newFriendsDBManager = getNewFriendsDBManager();
        int i = 0;

        try {
            i = newFriendsDBManager.queryAllNewFriendsUnRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 得到群通知未读的数量
     *
     * @param
     */
    public int getGroupNoticveUnreadCount() {

        groupNoticeDBManager = getGroupNoticeDBManager();
        int i = 0;

        try {
            i = groupNoticeDBManager.queryAllGroupNoticeUnRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 查询得到所有好友
     *
     * @return
     */
    public List<User> getallFriends() {
        friendsDBManager = getFriendsDBManager();
        List<User> users = null;
        try {
            users = friendsDBManager.queryAllFriends();
            for (User user : users) {
                if (user.getReMark() == null || user.getReMark().equals("")) {
                    user.setReMark(user.getNickName());
                }
                if (user.getAvatar() == null) {
                    user.setAvatar("");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }

    /**
     * 查询得到一个好友
     *
     * @return
     */
    public User getOneFriendById(int userId) {
        friendsDBManager = getFriendsDBManager();
        User user = null;
        try {
            user = friendsDBManager.queryById(userId);
            if (user == null) {
                user = new User();
                user.setId(userId);
                user.setAvatar("");
                user.setNickName(String.valueOf(userId));
                user.setIsBother(false);
                user.setIsTop(false);
                user.setReMark(String.valueOf(userId));
                user.setLoginUserId(loginUserId);
                user.setSex("M");
                user.setType(User.PERSONALFRIEND);
                user.setExist(false);

            } else {
                if (user.getReMark() == null || "".equals(user.getReMark())) {
                    user.setReMark(user.getNickName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;

    }

    /**
     * 根据关键字查询好友（关键字可能是好友 id 昵称或者备注）
     *
     * @param keyword
     * @return
     */
    public List<User> searchFriendsByKeyword(String keyword) {
        friendsDBManager = getFriendsDBManager();
        List<User> users = new ArrayList<>();
        try {
            users = friendsDBManager.queryFriendsByKeyword(keyword);
            if (users == null) {
                users = new ArrayList<>();
            }
            for (User user : users) {
                if (user.getReMark() == null || user.getReMark().equals("")) {
                    user.setReMark(user.getNickName());
                }
                if (user.getAvatar() == null) {
                    user.setAvatar("");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }

    /**
     * 查询得到所有公众号
     *
     * @return
     */
    public List<User> getallOfficialNumber() {
        friendsDBManager = getFriendsDBManager();
        List<User> users = null;
        try {
            users = friendsDBManager.queryAllOfficialNumber();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }

    /**
     * 查询得到一个公众号
     *
     * @return
     */
    public User getOneOfficialNumber(int userId) {
        friendsDBManager = getFriendsDBManager();
        User user = null;
        try {
            user = friendsDBManager.queryById(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;

    }

    /**
     * 查询得到一个用户
     *
     * @return
     */
    public User getOneUserById(int userId) {
        return getOneUserById(userId, UserEvent.EVENT_DEFAULT);
    }

    public User getOneUserById(int userId, final int eventType) {
        userDBManager = getUserDBManager();
        User user = null;
        try {
            user = userDBManager.queryById(userId);
            if (user == null) {
                user = new User();
                user.setId(userId);
                user.setAvatar("");
                user.setNickName(String.valueOf(userId));
                user.setIsBother(false);
                user.setIsTop(false);
                user.setReMark(String.valueOf(userId));
                user.setLoginUserId(loginUserId);
                user.setSex("M");
                user.setType(0);
                if (userId != 0) {
                    GetHttpUtil.getUserInfo(userId, mContext, new GetHttpUtil.GetUserListener() {
                        @Override
                        public void onGetUserSuccess(User user) {
                            //用户不存在，请求后发送事件
                            UserEvent event = new UserEvent(eventType);
                            event.setUser(user);
                            EventBus.getDefault().post(event);

                            ChatListItem chatListItem = getChatListItem(user.getId(), 0);
                            if (chatListItem != null) {
                                EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.UPDATE));
                            }
                        }

                        @Override
                        public void onGetUserFail() {

                        }
                    });
                }

                user.setExist(false);
            } else {
                if (user.getReMark() == null || "".equals(user.getReMark())) {
                    user.setReMark(user.getNickName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;

    }

    /**
     * 根据id 查询是否是好友
     *
     * @param userId
     * @return
     */
    public boolean queryIsFriend(int userId) {
        friendsDBManager = getFriendsDBManager();
        return friendsDBManager.queryIsFriend(userId);
    }

    /**
     * 查询得到一个陌生用户
     *
     * @return
     */
    public User getStrangerById(int userId) {
        userDBManager = getUserDBManager();
        User user = null;
        try {
            user = userDBManager.queryById(userId);
            if (user == null) {
                user = new User();
                user.setId(userId);
                user.setAvatar("");
                user.setNickName(String.valueOf(userId));
                user.setIsBother(false);
                user.setIsTop(false);
                user.setReMark(String.valueOf(userId));
                user.setLoginUserId(loginUserId);
                user.setSex("M");
                user.setType(0);
            } else {
                if (user.getReMark() == null || "".equals(user.getReMark())) {
                    user.setReMark(user.getNickName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;

    }

    /**
     * 新的好友信息
     *
     * @param loadedCount 界面上已经加载的数量
     * @return
     */
    public List<User> getNewFriendsInfo(int loadedCount) {
        newFriendsDBManager = getNewFriendsDBManager();
        List<User> newFriends = null;
        try {
            newFriends = newFriendsDBManager.queryAllNewFriends(loadedCount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFriends;
    }

    /**
     * 新的好友信息
     *
     * @param userId 界
     * @return
     */
    public User getOneApplyAddFriend(int userId) {
        newFriendsDBManager = getNewFriendsDBManager();
        User user = null;
        try {
            user = newFriendsDBManager.queryById(userId, loginUserId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 获取群通知消息列表
     *
     * @return
     * @loadedCount 已经加载的数量
     */
    public List<ApplyGroupNotice> getGroupNoticeList(int loadedCount) {
        groupNoticeDBManager = getGroupNoticeDBManager();
        List<ApplyGroupNotice> list = null;
        try {
            list = groupNoticeDBManager.queryAllGroupNotices(loadedCount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 新增或更新聊天列表
     *
     * @param chatListItems
     */
    public void insertOrUpdateChatList(List<ChatListItem> chatListItems) {
        chatListDBManager = getChatListDBManager();
        if (chatListItems != null) {
            try {
                chatListDBManager.insertOrUpdateChatList(chatListItems);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 新增或更新聊天列表
     *
     * @param item
     */
    public void insertOrUpdateChatList(ChatListItem item) {
        chatListDBManager = getChatListDBManager();
        if (item != null) {
            try {
                chatListDBManager.insertOrUpdateChatList(item);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询所有聊天列表
     *
     * @return
     */

    public List<ChatListItem> getAllChatList() {
        List<ChatListItem> chatList = new ArrayList<>();
        chatListDBManager = getChatListDBManager();
        groupDBManager = getGroupDBManager();
        messageDBManager = getMessageDBManager();
        friendsDBManager = getFriendsDBManager();
        //UNREADCOUNT = 0;

        try {
            chatList = chatListDBManager.queryAll();
            for (ChatListItem chatListItem : chatList) {

                int chatType = chatListItem.getChatType();


                if (chatType == 0 || chatType == 2) {//0 单聊用户 2公众号用户
//                    User user = getOneFriendById(chatListItem.getUserId());
//
//                    //friend表没有，从useri表中查询
//                    if (user.getNickName().equals(String.valueOf(user.getId()))){
                    User user = getOneUserById(chatListItem.getUserId());
                    //   user.setNickName(String.valueOf(user.getId()));
                    // user.setReMark(String.valueOf(user.getId()));

                    //  }

                    chatListItem.setAvatar(user.getAvatar());
                    chatListItem.setIsBother(user.getIsBother());
                    chatListItem.setIsTop(user.getIsTop());
                    chatListItem.setUser(user);
                    if (user.getReMark() == null || (
                            user.getReMark() != null && user.getReMark().equals(""))) {
                        chatListItem.setName(user.getNickName());
                    } else {
                        chatListItem.setName(user.getReMark());
                    }
                    IMStruct002 im0 = JFMessageManager.getInstance().getLastMessage(chatListItem.getUserId(), (byte) 0);
                    chatListItem.setStruct002(im0);
                    //chatListItem.setStruct002(imStruct002);
                } else {
//                    Group group = getGroupWithUsersInGroups(chatListItem.getUserId());
                    Group group = getGroup(chatListItem.getUserId(), false);
                    chatListItem.setAvatar(group.getAvatar());
                    chatListItem.setIsBother(group.getIsBother());
                    chatListItem.setIsTop(group.getIsTop());
                    chatListItem.setName(group.getGroupName());
                    //chatListItem.setStruct002(imStruct002);
                    chatListItem.setGroup(group);
                    IMStruct002 im0 = JFMessageManager.getInstance().getLastMessage(chatListItem.getUserId(), (byte) 1);
                    chatListItem.setStruct002(im0);
                }

                int num = JFMessageManager.getInstance().getUnReadCount(chatListItem.getUserId(),
                        (byte) chatType);
                if (chatType == 2) {//公众号查询未读数量 type是0
                    num = JFMessageManager.getInstance().getUnReadCount(chatListItem.getUserId(),
                            (byte) 0);
                }

                if (num == 0) {
                    num = -1;
                }
                //免打扰群组如果有未读不显示角标 显示红点
                if (chatType == 1 && num != -1 && chatListItem.getIsBother()) {
                    //JFMessageManager.getInstance().unreadZero(chatListItem.getUserId(),StructFactory.TO_USER_TYPE_GROUP);
                    num = 0;
                }
                //处理应用号不显示角标--------
                String chatIdNotReachedByChatListItem = EnvironmentVariable.getProperty("ChatIdNotReachedByChatListItem", "");
                if (!chatIdNotReachedByChatListItem.equals("")) {
                    String[] chatIdNotReachedByChatListItemArray = chatIdNotReachedByChatListItem.split(",");
                    for (int i = 0; i < chatIdNotReachedByChatListItemArray.length; i++) {
                        if (chatIdNotReachedByChatListItemArray[i].equals(chatListItem.getUserId() + "")) {
                            break;
                        }
                        if (i == chatIdNotReachedByChatListItemArray.length - 1) {
                            chatListItem.setBadgernum(num);
                        }

                    }
                } else {
                    chatListItem.setBadgernum(num);
                }
                //-------------------------
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return chatList;

    }

    public ChatListItem getChatListItem(int userId, int chatType) {
        ChatListItem chatListItem = null;
        chatListDBManager = getChatListDBManager();
        //userDBManager = getUserDBManager();
        groupDBManager = getGroupDBManager();
        messageDBManager = getMessageDBManager();
        friendsDBManager = getFriendsDBManager();

        try {
            chatListItem = chatListDBManager.queryChatListItem(userId, chatType);

            // int type = chatListItem.getChatType();
            if (chatListItem != null) {
                int num = JFMessageManager.getInstance().getUnReadCount(chatListItem.getUserId(),
                        (byte) chatType);
                if (num == 0) {
                    num = -1;
                }
                chatListItem.setBadgernum(num);
//                IMStruct002 imStruct002 = messageDBManager.queryForID(chatListItem.getStruct002()
//                        .getMessageID());

                if (chatType == 0 || chatType == 2) {
//                    User user = getOneFriendById(chatListItem.getUserId());
//
//                    //friend表没有，从useri表中查询
//                    if (user.getNickName().equals(String.valueOf(user.getId()))) {
//                        user = getOneUserById(chatListItem.getUserId());
//                        user.setNickName(String.valueOf(user.getId()));
//                        user.setReMark(String.valueOf(user.getId()));
//
//                    }
                    User user = getOneUserById(chatListItem.getUserId());

                    chatListItem.setAvatar(user.getAvatar());
                    chatListItem.setIsBother(user.getIsBother());
                    chatListItem.setIsTop(user.getIsTop());
                    chatListItem.setUser(user);
                    if (user.getReMark() == null || (
                            user.getReMark() != null && user.getReMark().equals(""))) {
                        chatListItem.setName(user.getNickName());
                    } else {
                        chatListItem.setName(user.getReMark());
                    }
                    IMStruct002 im0 = JFMessageManager.getInstance().getLastMessage(chatListItem.getUserId(), (byte) 0);
                    chatListItem.setStruct002(im0);
                    //chatListItem.setStruct002(imStruct002);

                } else {
                    Group group = getGroup(chatListItem.getUserId(), false);

                    chatListItem.setAvatar(group.getAvatar());
                    chatListItem.setIsBother(group.getIsBother());
                    chatListItem.setIsTop(group.getIsTop());
                    chatListItem.setName(group.getGroupName());
                    // chatListItem.setStruct002(imStruct002);
                    chatListItem.setGroup(group);
                    IMStruct002 im0 = JFMessageManager.getInstance().getLastMessage(chatListItem.getUserId(), (byte) 1);
                    chatListItem.setStruct002(im0);

                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return chatListItem;

    }

    /**
     * 删除一个聊天列表
     *
     * @param item
     */
    public void deleteChatListiItem(ChatListItem item) {
        chatListDBManager = getChatListDBManager();
        try {
            chatListDBManager.delete(item);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 插入或更新群组
     *
     * @param group
     */
    public void insertOrUpdateGroup(Group group) {
        groupDBManager = getGroupDBManager();
        try {
            groupDBManager.insertOrUpdate(group);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 插入或更新群组，但是不插入myGroup数据库
     */
    public void insertOrUpdateUSERGroup(Group group) {
        groupDBManager = getGroupDBManager();
        try {
            groupDBManager.insertOrUpdateExceptMyGroup(group);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    /**
//     * 插入或更新群组
//     *
//     * @parm groups
//     */
//    public  void insertOrUpdateGroup(List<Group> groups) {
//        groupDBManager = getGroupDBManager();
//        try {
//            groupDBManager.insertOrUpdate(groups);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }

    /**
     * 登录时获取群组列表数据库操作
     *
     * @parm groups
     */
    public void insertGroup(List<Group> groups) {
        groupDBManager = getGroupDBManager();
        try {
            groupDBManager.insert(groups);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 向群组中插入联系人
     *
     * @param groupId
     * @param users
     */
    public void insertorUpdateMyGroupUser(int groupId, List<User> users) {
        groupDBManager = getGroupDBManager();
        userDBManager = getUserDBManager();
        try {
            userDBManager.insertOrReplace(users);
//            for (User user : users) {
//                // groupDBManager.insertOrUpdateUser(groupId, user.getId());//9.25屏蔽
//                groupDBManager.insertOrUpdateUser(groupId, user);
//            }
            groupDBManager.insertOrUpdateUser(groupId, users);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 向群组中插入管理员
     *
     * @param groupId
     * @param user
     */
    public void insertorUpdateGroupManager(int groupId, User user) {
        groupDBManager = getGroupDBManager();
        try {
            groupDBManager.insertOrUpdateUser(groupId, user);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 向群组中插入联系人
     *
     * @param groupId
     * @param userId
     */
    public void insertOrUpdateMyGroupUser(int groupId, int userId) {
        groupDBManager = getGroupDBManager();
        try {
            groupDBManager.insertOrUpdateUser(groupId, userId);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 删除群组中的所有成员
     *
     * @param groupId
     */
    public void removeAllUsserByGroupId(int groupId) {
        groupDBManager = getGroupDBManager();
        try {
            groupDBManager.deleteAllGroupUser(groupId);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 向群组中插入联系人（有备注）
     *
     * @param groupId
     * @param user
     */
    public void insertOrUpdateMyGroupUser(int groupId, User user) {
        groupDBManager = getGroupDBManager();
        try {
            groupDBManager.insertOrUpdateUser(groupId, user);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 根据id 查询群组(一并返回群成员)
     *
     * @param id
     * @return
     */
    public Group getGroupWithUsers(int id) {
        return getGroup(id, true);
    }

    public Group getGroup(int id, boolean withUser) {
        Group group = null;
        try {
            groupDBManager = getGroupDBManager();
            if (withUser) {
                group = groupDBManager.queryByIdWithUser(id);
            } else {
                group = groupDBManager.queryByIdWithoutUser(id);

            }


            if (group == null) {
                group = new Group();
                group.setGroupName(String.valueOf(id));
                group.setGroupId(id);
                group.setAvatar("");
                group.setUsers(new ArrayList<User>());
                group.setIsTop(false);
                group.setLoginUserId(loginUserId);
                group.setIsBother(false);
                group.setExist(false);
            } else {
                if (group.getAvatar() == null) {
                    group.setAvatar("");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return group;
    }

    /**
     * 根据关键字查询群组（关键字可能是群号 ）
     *
     * @param keyword
     * @return
     */
    public List<Group> searchGroupByKeyword(String keyword) {
        groupDBManager = getGroupDBManager();
        List<Group> groups = new ArrayList<>();
        try {
            groups = groupDBManager.queryGroupByKeyword(keyword);
            if (groups == null) {
                groups = new ArrayList<>();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return groups;
    }

    /**
     * 根据id 查询群组,只查询Groups中的，不查询MyGroup里的
     *
     * @param id
     * @return
     */
    public Group getGroupWithUsersInGroups(int id) {
        return getGroupInGroups(id, true);
    }

    /**
     * 根据id 查询群组,只查询Groups中的，不查询MyGroup里的
     *
     * @param id
     * @param withUser 是否查询群成员
     * @return
     */
    public Group getGroupInGroups(int id, boolean withUser) {
        Group group = null;
        try {
            groupDBManager = getGroupDBManager();
            group = groupDBManager.queryByIdWithUserInGroups(id, withUser);

            if (group == null) {
                group = new Group();
                group.setGroupName(String.valueOf(id));
                group.setGroupId(id);
                group.setAvatar("");
                group.setUsers(new ArrayList<User>());
                group.setIsTop(false);
                group.setLoginUserId(loginUserId);
                group.setIsBother(false);
            } else {
                if (group.getAvatar() == null) {
                    group.setAvatar("");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return group;
    }

    /**
     * 得到群组中用户的信息，返回的user 只包含id，和群组昵称
     *
     * @param groupId
     * @param userId
     * @return
     */
    public User getGroupUserInfo(int groupId, int userId) {
        groupDBManager = getGroupDBManager();
        User user = null;
        try {
            user = groupDBManager.queryGroupUser(groupId, userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;

    }

    /**
     * 查询所有群组
     *
     * @return
     */
    public List<Group> getallGroupWithUsers() {
        groupDBManager = getGroupDBManager();
        return groupDBManager.queryAll(true);
    }

    /**
     * 查询所有群组（不带群成员）
     *
     * @return
     */
    public List<Group> getallGroupWithOutUsers() {
        groupDBManager = getGroupDBManager();
        return groupDBManager.queryAll(false);
    }

    public void quitGroup(int userId, int groupId) {
        groupDBManager = getGroupDBManager();
        try {
            groupDBManager.quitGroup(userId, groupId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过id查询我的群组是否存在
     *
     * @param groupId
     * @return
     */
    public boolean queryMyGroupExist(int groupId) {
        groupDBManager = getGroupDBManager();
        return groupDBManager.queryMyGroupExist(groupId);
    }

    /**
     * 获取群组中的某个人员信息
     *
     * @param groupId
     * @param userId
     * @return
     */
    public User getGroupUser(int groupId, int userId) {
        groupDBManager = getGroupDBManager();
        return groupDBManager.getGroupUser(groupId, userId);
    }

    /**
     * 保存消息
     *
     * @param imStruct002
     */
    public void insertOrReplaceMsg(IMStruct002 imStruct002) {
        messageDBManager = getMessageDBManager();
        try {
            messageDBManager.insert(imStruct002);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除聊天记录
     */
    public void deleteChatRecord(int chatUserId) {
        messageDBManager = getMessageDBManager();
        //  messageDBManager.deleteAll(chatUserId);
    }

    /**
     * 删除聊天记录
     */
    public void deleteFriend(int friendId) {
        friendsDBManager = getFriendsDBManager();
        friendsDBManager.delete(friendId);
    }

    /**
     * 得到manager实例
     *
     * @return
     */
    private UserDBManager getUserDBManager() {
        if (userDBManager == null) {
            userDBManager = new UserDBManager();
        }

        return userDBManager;
    }

    public FriendsDBManager getFriendsDBManager() {
        if (friendsDBManager == null) {
            friendsDBManager = new FriendsDBManager();
        }

        return friendsDBManager;
    }

    private GroupDBManager getGroupDBManager() {
        if (groupDBManager == null) {
            groupDBManager = new GroupDBManager();
        }

        return groupDBManager;
    }

    private NewFriendsDBManager getNewFriendsDBManager() {
        if (newFriendsDBManager == null) {
            newFriendsDBManager = new NewFriendsDBManager();
        }

        return newFriendsDBManager;
    }

    private com.efounder.message.db.MessageDBManager getMessageDBManager() {
        if (messageDBManager == null) {
            //messageDBManager = new MessageDBManager(GetDBHelper.getInstance().);
            messageDBManager = MessageDBManager.getInstance();
        }

        return messageDBManager;
    }

    private ChatListDBManager getChatListDBManager() {
        if (chatListDBManager == null) {
            chatListDBManager = new ChatListDBManager();
        }

        return chatListDBManager;
    }

    private GroupNoticeDBManager getGroupNoticeDBManager() {
        if (groupNoticeDBManager == null) {
            groupNoticeDBManager = new GroupNoticeDBManager();
        }
        return groupNoticeDBManager;
    }

    /**
     * 刷新 wechatdbmanager
     */
    public void refresh() {
        groupNoticeDBManager = null;
        chatListDBManager = null;
        newFriendsDBManager = null;
        groupDBManager = null;
        friendsDBManager = null;
        userDBManager = null;
        Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID, "0")).intValue();
    }
}
